﻿using RuTracker.Interface;
using RuTracker.Interface.Login;
using RuTrackerLib.ServiceAttibutes;
using RuTrackerLib.Tracker;

namespace RuTrackerLib.Login
{
    [PerApplicationService]
    public class LoginProcessor : ILoginProcessor
    {
        private readonly ITrackerAccessor _accessor;
        private readonly IUserRepository _userRepository;

        public LoginProcessor(ITrackerAccessor accessor, IUserRepository userRepository)
        {
            _accessor = accessor;
            _userRepository = userRepository;
        }

        public LoginResults Login(string userName, string password)
        {
            var result = LoginToSite(userName, password);
            if (result.Succeeded)
            {
                RegisterUserInSystem(userName, password);   
            }
            return result;
        }

        public LoginResults LoginWithCaptcha(string userName, string password, string captchaCode, string captchaCodeValue, string captchaSid)
        {
            var result = LoginToSite(userName, password, captchaCode, captchaCodeValue, captchaSid);
            if (result.Succeeded)
            {
                RegisterUserInSystem(userName, password);
            }
            return result;
        }

        private void RegisterUserInSystem(string userName, string password)
        {
            User user = _userRepository.GetUser(userName);
            if (user != null)
            {
                if (user.Password != password)
                {
                    user.Password = password;
                    _userRepository.UpdateUser(user);   
                }
            }
            else
            {
                _userRepository.CreateUser(userName, password, string.Empty);
            }
        }

        private LoginResults LoginToSite(string userName, string password)
        {
            if (_accessor.IsSignedIn())
            {
                _accessor.SignOut();
            }

            return _accessor.SignIn(userName, password);
        }

        private LoginResults LoginToSite(string userName, string password, string captchaCode, string captchaCodeValue, string captchaSid)
        {
            if (_accessor.IsSignedIn())
            {
                _accessor.SignOut();
            }

            return _accessor.SignInWithCapture(userName, password, captchaCode, captchaCodeValue, captchaSid);
        }
    }
}
